use std::collections::HashMap;

use crate::mir::instr::Operand;

pub struct ScopeStack {
    scopes: Vec<HashMap<String, Operand>>
}

impl ScopeStack {
    pub fn new() -> Self {
        Self { scopes: vec![HashMap::new()] } // 全局作用域
    }

    pub fn enter_scope(&mut self) {
        self.scopes.push(HashMap::new());
    }

    pub fn exit_scope(&mut self) {
        self.scopes.pop();
    }

    pub fn insert(&mut self, name: String, val: Operand) {
        self.scopes.last_mut().unwrap().insert(name, val);
    }

    pub fn lookup(&self, name: &str) -> Option<&Operand> {
        for scope in self.scopes.iter().rev() {
            if let Some(v) = scope.get(name) {
                return Some(v);
            }
        }
        None
    }

    pub fn lookup_mut(&mut self, name: &str) -> Option<&mut Operand> {
        for scope in self.scopes.iter_mut().rev() {
            if let Some(v) = scope.get_mut(name) {
                return Some(v);
            }
        }
        None
    }
}

